import React from "react";
import {Button, Upload} from "antd";
import BaseComponent from "../../../redare/components/BaseComponent";
import {RESOURCE_SERVICE, uploadFileType} from "../../../common/ConstField";

import {DownloadOutlined, UploadOutlined} from "@ant-design/icons/lib/icons";
import {ifTrue} from "../../../redare/utils/Utils";
import axios from "axios";

export default class FileUpload extends BaseComponent {

  static defaultProps = {
    isMultiple: false, //是否多个文件上传
    isOneHideUploadBtn: false, //是否单个文件上传时隐藏按钮
    uploadFileType: undefined,
    style: {}
  };

  //文件上传数量
  fileUploadNum = 1;
  //删除的文件
  delFileArray = [];

  state = {
    fileList: []
  };

  constructor(props) {
    super(props);
    if (this.props.isMultiple) {
      this.isMultiple = true;
    }
  }

  getData() {

    let addList = [];
    let delFileIdList = [];
    let fileList = this.state.fileList;
    let delFileArray = this.delFileArray;

    if (fileList && fileList.length > 0) {
      fileList.map((item) => {
        if (item.response && item.response.data) {
          addList.push(item.response.data)
        }
      });
    }

    if (delFileArray && delFileArray.length > 0) {
      delFileArray.map((item) => {
        if (item.id) {
          delFileIdList.push(item.id)
        }
      });
    }

    return {
      addFileList: addList,
      delFileList: delFileArray,
      delFileIdList: delFileIdList
    };
  }

  getFileList() {
    return this.state.fileList;
  }

  getAddData() {
    let addList = null;
    let fileList = this.state.fileList;

    if (fileList && fileList.length > 0) {
      addList = [];
      fileList.map((item) => {
        if (item.response && item.response.data) {
          addList.push(item.response.data)
        }
      });
    }
    return addList;
  }

  getDelData() {
    return this.delFileArray;
  }

  setData(data) {
    this.delFileArray = [];
    if (data && data.constructor === Array) {
      data.map((item) => {
        item.uid = "temp_" + item.id;
        item.status = 'done';
      });
      if (ifTrue(this.isMultiple)) {
        //非单选时自动扩容
        this.fileUploadNum = this.fileUploadNum + data.length;
      }
      this.setState({fileList: data});
    }
  }

  clearData() {
    this.setState({fileList: []});
  }

  render() {

    let className;
    if (this.props.className) {
      className = this.props.className;
    }

    return (
      <>

        <div style={this.props.style}>
          <Upload
            name='file'
            className={className}
            accept={this.props.uploadFileType ? this.props.uploadFileType : uploadFileType}
            action={RESOURCE_SERVICE.FILE}
            fileList={this.state.fileList}
            multiple={true}
            customRequest={(req) => {
              let forms = new FormData()
              forms.append("file", req.file);

              let postFn = () => {
                axios.post(req.action, forms, {
                  onUploadProgress(progress) {
                    req.onProgress({percent: Math.round(progress.loaded / progress.total * 100)}, req.file);
                  }
                }).then((s_r) => {
                  req.onSuccess(s_r.data, req.file);
                }).catch((f_r) => {
                  req.onError(f_r);
                });
              };

              setTimeout(() => {
                postFn();
              }, 100);


              // 2020-10-27 00:47:30 使用这个就不需要 setTimeout，当然也就无法使用 onProgress
              // uploadFile(req.file).then((s_r)=>{
              //     console.log("s_r");
              //     req.onSuccess(s_r, req.file);
              // });

            }}
            onChange={(info) => {
              this._onChange(info)
            }}
            showUploadList={{
              showDownloadIcon: true,
              downloadIcon: <DownloadOutlined/>,
              showRemoveIcon: true
            }}
            onDownload={(file) => {
              let uri = file.uri;
              let name = file.name
              try {
                window.location.href = uri + "?downLoad=true&fileName=" + name;
              } catch (e) {
                console.error("附件下载错误", e);
              }
            }}
            onRemove={(file) => {
              //id存在，说明是来自于业务文件
              if (file.id) {
                this.delFileArray.push(file);
              }
            }}
          >

            {
              (!this.props.isOneHideUploadBtn || this.state.fileList.length <= 0) && (
                <Button>
                  <UploadOutlined/>上传文件
                </Button>
              )
            }

          </Upload>

        </div>
      </>
    )

  }


  _onChange(info) {

    console.log(info)

    let fileUploadNum = this.fileUploadNum;
    let fileList = [...info.fileList];

    // if( fileList.length === 0 ){
    //     return;
    // }

    if (ifTrue(this.isMultiple) && fileUploadNum - fileList.length <= 2) {
      //非单选时自动扩容
      fileUploadNum = fileUploadNum + 2;
      this.fileUploadNum = fileUploadNum;
    }
    fileList = fileList.slice(-fileUploadNum);
    let fail = false;
    fileList = fileList.map((file, index) => {
      if (file.response && (file.response.code == 1 || !file.response.data)) {
        fail = true;
        fileList.splice(index, 1);
      } else if (file.response && file.response.code == 0) {
        file.response.data.type = file.response.data.mediaType;
        file.response.data.uri = file.response.data.url;
        file.uri = file.response.data.url;
      }
      return file;
    });
    if (fail) {
      this.toastFail("文件上传失败");
      return;
    }

    //此方法只是为了触此组件被 Form.Item 包裹时的验证
    if (this.props.onChange && this.props.onChange.constructor === Function) {
      this.props.onChange({});
    }

    this.setState({fileList});
  }
}